package com.zgs.mall.product.exception;

import com.zgs.common.exception.BizCodeEnum;
import com.zgs.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
//@ControllerAdvice(basePackages = "com.zgs.mall.product.controller")
@RestControllerAdvice(basePackages = "com.zgs.mall.product.controller")
public class MallExceptionControllerAdvice {
    //告诉springmvc能处理什么异常
    //@ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现异常{},异常类型{}",getStackTrace(e),e.getClass());
        BindingResult result = e.getBindingResult();
            Map<String,String> map= new HashMap<String,String>();
            //获取校验的错误结果
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach((itme)->{
                //FieldError 获取到错误提示
                String defaultMessage = itme.getDefaultMessage();
                String field = itme.getField();
                map.put(field,defaultMessage);
            });
            return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        log.error("数据校验出现异常{},异常类型{}",getStackTrace(e),e.getClass());
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg() );
    }

    public static String getStackTrace(Throwable throwable)
    {
        StringWriter sw = new StringWriter();

        PrintWriter pw = new PrintWriter(sw);
        try
        {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally
        {
            pw.close();
        }
    }
}
